package demo1;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;

/**
 * @Author liangzai
 * @Description:
 */
public class Chat extends JFrame implements ActionListener {
    public JScrollBar scrollBar;
    public JTextField inputMap;
    public Socket socket;
    public DefaultListModel listModel = new DefaultListModel();

    //10
    public void connServer(){
        try {
            socket = new Socket("10.190.178.80",9999);
            InputStream inputStream = socket.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            String line = null;
            while((line=dataInputStream.readUTF())!=null){
                listModel.addElement(line);
                scrollBar.setValue(scrollBar.getMaximum());
            }

            dataInputStream.close();
            inputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void init(String title,int wight, int hight){
        listModel.addElement("hello");
        listModel.addElement("world");

        JList jList = new JList(listModel);
        JScrollPane scrollPane = new JScrollPane(jList);
        scrollBar = scrollPane.getVerticalScrollBar();
        this.add(scrollPane, BorderLayout.CENTER);
        JPanel panel = new JPanel(new BorderLayout());
        inputMap = new JTextField();
        panel.add(inputMap,BorderLayout.CENTER);
        JButton sendBut = new JButton("发送");
        sendBut.addActionListener(this);
        panel.add(sendBut,BorderLayout.EAST);

        this.add(panel,BorderLayout.SOUTH);


        this.setTitle(title);

        this.setSize(wight,hight);

        this.setVisible(true);

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        this.setLocationRelativeTo(null);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String msg = inputMap.getText().toString().trim();
        try {
            OutputStream outputStream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeUTF(msg);
            dataOutputStream.flush();
            inputMap.setText("");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
